package com.easybuy.controller;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.easybuy.pojo.Order;
import com.easybuy.pojo.Order_detail;
import com.easybuy.pojo.Product;
import com.easybuy.pojo.User;
import com.easybuy.service.OrderService;
import com.easybuy.service.Order_detailService;
import com.easybuy.service.ProductService;
import com.easybuy.service.UserService;
import com.easybuy.util.BuyCar;

import net.spy.memcached.MemcachedClient;

@Controller
@RequestMapping("/Car")
public class BuyCarController {
	private static MemcachedClient mcc;
	private static List<BuyCar> listcar;
	private static String serialNumber;
	static {
		try {
			mcc = new MemcachedClient(new InetSocketAddress("127.0.0.1",11211));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@Autowired
	ProductService productService;
	
	@Autowired
	UserService userService;
	
	@Autowired
	OrderService orderService;
	
	@Autowired
	Order_detailService order_detailService;
	
	
	
	public static String getRandomStringByLength() {
        String base = "ABCDEF0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 32; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }
	
//	购物车结算页面改变购物车数量
	@RequestMapping("/addcar1")
	@ResponseBody
	public boolean addcar1(@RequestParam(required = false) String userName,
			@RequestParam(required = false) String id,
			@RequestParam(required = false) String count1) {
		listcar = (List<BuyCar>) mcc.get(userName);
		int bid1 = Integer.parseInt(id);
		for (int i=0;i<listcar.size();i++) {
			if (listcar.get(i).getId()==bid1) {
				Product product = productService.selectProductsById(bid1);
				 int stock = product.getStock();
				 if (Integer.parseInt(count1)>stock) {
					 return false;
				}
				listcar.get(i).setCount(Integer.parseInt(count1));
				break;
			}
		}
		mcc.set(userName, 2592000, listcar);
		return true;
	}
	
//商品列表和商品详情加入购物车
	@RequestMapping("/addCar")
	@ResponseBody
	public boolean addcars(@RequestParam(required = false) String userName,
			@RequestParam(required = false) String id,
			@RequestParam(required = false) String count){
		int bid = Integer.parseInt(id);
		boolean flag = false;
		if(mcc.get(userName)==null) {
			 listcar = new ArrayList<BuyCar>();
			 Product product = productService.selectProductsById(bid);
			 int stock = product.getStock();
			 if (Integer.parseInt(count)>stock) {
				return false;
			 }
			 BuyCar buyCar = new BuyCar();
			 buyCar.setCount(Integer.parseInt(count));
			 buyCar.setFileName(product.getFileName());
			 buyCar.setId(bid);
			 buyCar.setName(product.getName());
			 buyCar.setPrice(product.getPrice());
			 listcar.add(buyCar);
			 flag = true;
		}else {
			listcar = (List<BuyCar>) mcc.get(userName);
			if (listcar.size()==0) {
				 Product product = productService.selectProductsById(bid);
				 int stock = product.getStock();
				 if (Integer.parseInt(count)>stock) {
					 return false;
				}
				 BuyCar buyCar = new BuyCar();
				 buyCar.setCount(Integer.parseInt(count));
				 buyCar.setFileName(product.getFileName());
				 buyCar.setId(bid);
				 buyCar.setName(product.getName());
				 buyCar.setPrice(product.getPrice());
				 listcar.add(buyCar);
				 flag = true;
			}else {
				for (int i=0;i<listcar.size();i++) {
					if (listcar.get(i).getId()==bid) {
						Product product = productService.selectProductsById(bid);
						 int stock = product.getStock();
						 if (listcar.get(i).getCount()+Integer.parseInt(count)>stock) {
							 return false;
						}
						listcar.get(i).setCount(listcar.get(i).getCount()+Integer.parseInt(count));
						flag = true;
						break;
					}
				}
				if (!flag) {
					 Product product = productService.selectProductsById(bid);
					 int stock = product.getStock();
					 if (Integer.parseInt(count)>stock) {
						 return false;
					 }
					 BuyCar buyCar = new BuyCar();
					 buyCar.setCount(Integer.parseInt(count));
					 buyCar.setFileName(product.getFileName());
					 buyCar.setId(bid);
					 buyCar.setName(product.getName());
					 buyCar.setPrice(product.getPrice());
					 listcar.add(buyCar);
					 flag = true;
				}
			}
		}	
		mcc.set(userName, 2592000, listcar);
		return flag;
	}
	
//	购物车显示
	@RequestMapping("/selectCars")
	@ResponseBody
	public List<BuyCar> selectCar(@RequestParam(required = false) String userName){
		
		if (mcc.get(userName)!=null) {
			listcar = (List<BuyCar>) mcc.get(userName);
		}else {
			listcar = new ArrayList<BuyCar>();
		}
		return listcar;
	}
	
	@RequestMapping("/delete")
	@ResponseBody
	public boolean delete(@RequestParam String id,@RequestParam String userName) {
		boolean flag = false;
		listcar = (List<BuyCar>) mcc.get(userName);
		for (int i = 0; i < listcar.size(); i++) {
			if (listcar.get(i).getId()==Integer.parseInt(id)) {
				listcar.remove(i);
				mcc.set(userName, 2592000, listcar);
				flag = true;
				break;
			}
		}
		return flag;
	}
	
	@RequestMapping("/deleteAll")
	@ResponseBody
	public boolean deleteAll(@RequestParam String userName) {
		mcc.delete(userName);
		return true;
	}
	
	
	@RequestMapping("/order")
	@ResponseBody
	public void addOrder(@RequestParam String userId,
			@RequestParam String userAddress) {
		User user = userService.selectUserById(Integer.parseInt(userId));
		String userName = user.getUserName();
		listcar = (List<BuyCar>) mcc.get(userName);
		float sumPrice = 0;
		for (BuyCar buyCar:listcar) {
			sumPrice = (float) (sumPrice+(buyCar.getCount()*buyCar.getPrice()));
		}
		Order order = new Order();
		order.setCost(sumPrice);
		order.setCreateTime(new Date());
		order.setLoginName(user.getLoginName());
		serialNumber = getRandomStringByLength();
		order.setSerialNumber(serialNumber);
		order.setUserAddress(userAddress);
		order.setUserId(Integer.parseInt(userId));
		orderService.insert(order);
		
		Order order2 = orderService.selectBySerialNumber(serialNumber);
		int orderId = order2.getId();
		for (BuyCar buyCar:listcar) {
			Order_detail order_detail = new Order_detail();
			order_detail.setCost((float) (buyCar.getPrice()*buyCar.getCount()));
			order_detail.setOrderId(orderId);
			order_detail.setProductId(buyCar.getId());
			order_detail.setQuantity(buyCar.getCount());
			order_detailService.insert(order_detail);
			Product product = productService.selectProductsById(buyCar.getId());
			product.setStock(product.getStock()-buyCar.getCount());
			productService.updateStock(product);
		}
		mcc.delete(userName);
	}
	
	@RequestMapping("/serchOrder")
	@ResponseBody
	public Order serchOrder() {
		return orderService.selectBySerialNumber(serialNumber);
	}
	
}
